package com.whitedust.top10;

import com.whitedust.structure.ListNode;

import java.util.List;

/**
 * @author A
 * @since 2025/11/2 9:35
 */

public class Top5 {


    private ListNode reverse(ListNode head) {
        ListNode pre = null;
        ListNode cur = head;
        ListNode next = null;
        while (cur != null) {
            next = cur.next;
            cur.next = pre;
            pre = cur;
            cur = next;
        }
        return pre;
    }

    public ListNode reverseKGroup(ListNode head, int k) {
        ListNode dummy = new ListNode(0);
        dummy.next = head;
        ListNode pre = dummy;
        ListNode end = dummy;
        while (end.next != null) {
            //找到区间的最后一个节点，如果是null，则说明不足k个，不需要反转
            for (int i = 0; i < k; i++) end = end.next;
            if (end == null) break;
            //start记录反转前的头节点，end是反转前的尾节点，next是反转区间的下一个节点，pre是反转区间的前面节点
            ListNode start = pre.next;
            ListNode next = end.next;
            //end.next = null;将反转区间从链表中分离出来，以便进行区间反转
            end.next = null;
            pre.next = reverse(start);
            start.next = next;
            //更新pre和end，准备下一次反转
            pre = start;
            end = pre;
        }
        return dummy.next;
    }
}
